package com.csun.cmny.provider.controller;

import com.alibaba.fastjson.JSON;
import com.csun.cmny.core.annotation.ValidateAnnotation;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.constant.Constant;
import com.csun.cmny.provider.dto.OrderApprovalDto;
import com.csun.cmny.provider.dto.OrderDto;
import com.csun.cmny.provider.dto.OrderQueryDto;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.OmcOrderService;
import com.csun.cmny.provider.utils.JPushService;
import com.csun.cmny.provider.utils.tfpt.YuanTongUtils;
import com.csun.cmny.provider.vo.OrderDetailVo;
import com.csun.cmny.provider.vo.OrderTaskVo;
import com.csun.cmny.provider.vo.OrderVo;
import com.csun.cmny.util.DateUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.sf.json.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-05-29 13:40
 * @Description: the class omc order controller
 */
@RestController
@RequestMapping(value = "/order", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class OmcOrderController extends BaseController {

    @Resource
    private JPushService jpushService;

    @Resource
    private CmnyMessageSource cmnyMessageSource;

    @Resource
    private OmcOrderService omcOrderService;

    /**
     * 下单
     *
     * @param orderDto  order dto
     *
     * @return  the wrapper.
     */
    @ValidateAnnotation
    //@LogAnnotation(isSaveRequestData = true, isSaveResponseData = true)
    @RequestMapping(value = "/apply", method = RequestMethod.POST)
    public Wrapper orderApply(@Validated @RequestBody OrderDto orderDto) {

        orderDto.setGroupId(getLoginAuthDto().getGroupId());

        Integer result = omcOrderService.orderApply(orderDto, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), result);
    }

    /**
     * 取消下单
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/cancelById/{id}", method = RequestMethod.POST)
    public Wrapper orderCancelById(@PathVariable Long id) {

        Integer result = omcOrderService.orderCancelById(id, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), result);
    }

    /**
     * 订单分页查询
     * @param orderQueryDto order query dto
     * @return  the wrapper.
     */
    @RequestMapping(value = "/queryListWithPage", method = RequestMethod.POST)
    public Wrapper queryOrderListWithPage(@RequestBody OrderQueryDto orderQueryDto) {

        orderQueryDto.setGroupId(getLoginAuthDto().getGroupId());
        PageInfo pageInfo = omcOrderService.queryOrderListWithPage(orderQueryDto);

        //return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), pageInfo);
    }

    /**
     * 根据Id查询订单
     *
     * @param id    id
     *
     * @return  the wrapper.
     */
    @RequestMapping(value = "/showById/{id}", method = RequestMethod.POST)
    public Wrapper showOrderById(@PathVariable Long id) {

        OrderDetailVo orderDetailVo = omcOrderService.showOrderById(id, getLoginAuthDto());

        //return WrapMapper.ok(orderDetailVo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), orderDetailVo);
    }

    /**
     * 查询待接单任务
     */
    @RequestMapping(value = "/showWaitRecvTask", method = RequestMethod.POST)
    public Wrapper showOrderWaitRecvTask() {

        List<OrderTaskVo> lists = omcOrderService.showOrderWaitRecvTask(getLoginAuthDto());

        //return WrapMapper.ok(lists);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), lists);
    }

    /**
     * 查询待服务任务
     */
    @RequestMapping(value = "/showWaitServiceTask", method = RequestMethod.POST)
    public Wrapper showOrderWaitServiceTask() {

        List<OrderTaskVo> lists = omcOrderService.showOrderWaitServiceTask(getLoginAuthDto());

        //return WrapMapper.ok(lists);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),lists);
    }

    /**
     * 查询订单任务
     *
     * @param orderQueryDto order query dto
     *
     * @return  the wrapper.
     */
    @RequestMapping(value = "/showTask", method = RequestMethod.POST)
    public Wrapper showOrderTask(@RequestBody OrderQueryDto orderQueryDto) {

        orderQueryDto.setGroupId(getLoginAuthDto().getGroupId());
        PageInfo pageInfo = omcOrderService.showOrderTask(orderQueryDto, getLoginAuthDto());

        //return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), pageInfo);
    }

    @RequestMapping(value = "/recvById/{id}", method = RequestMethod.POST)
    public Wrapper orderRecvById(@PathVariable Long id) {

        Integer result = omcOrderService.orderRecvById(id, getLoginAuthDto());

        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), result);
    }

    @RequestMapping(value = "/waiveById/{id}", method = RequestMethod.POST)
    public Wrapper orderWaiveById(@PathVariable Long id) {

        Integer result = omcOrderService.orderWaiveById(id, getLoginAuthDto());

        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),result);
    }

    @RequestMapping(value = "/checkInById/{id}", method = RequestMethod.POST)
    public Wrapper orderCheckInById(@PathVariable Long id) {

        Integer result = omcOrderService.orderCheckInById(id, getLoginAuthDto());

        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), result);
    }

    @RequestMapping(value = "/checkOutById/{id}", method = RequestMethod.POST)
    public Wrapper orderCheckOutById(@PathVariable Long id) {

        Integer result = omcOrderService.orderCheckOutById(id, getLoginAuthDto());

        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),result);
    }

    @RequestMapping(value = "/confirmById/{id}", method = RequestMethod.POST)
    public Wrapper orderConfirmById(@PathVariable Long id) {

        Integer result = omcOrderService.orderConfirmById(id, getLoginAuthDto());

        //提交区平台
        String login = YuanTongUtils.login(DateUtil.dateToStr1(new Date()));
        com.alibaba.fastjson.JSONObject retObj = JSON.parseObject(login);
        if (("" + retObj.get("code")).equals("1000")) {
            String vcode = retObj.getString("vcode");
//            查询服务商
            int serviceId = this.queryTfptService(getLoginAuthDto().getGroupName(), vcode);
            if (serviceId != 0) {
                //查询服务人员
                //根据id查询订单信息
                OrderDetailVo orderDetailVo = omcOrderService.showOrderById(id, getLoginAuthDto());
                String startDataString = DateUtil.dateToStr1(orderDetailVo.getServiceTime());
                String endDataString = DateUtil.dateToStr1(orderDetailVo.getEndTime());
                long differ = orderDetailVo.getEndTime().getTime() - orderDetailVo.getServiceTime().getTime();
                long hourM = 1000 * 60 * 60;
                int price = (int) (10l * differ/hourM);
                if (price==0){
                    price = 1;
                }
                String serviceStaff = YuanTongUtils.getServiceStaff(1, 100, serviceId, DateUtil.dateToStr1(new Date()), vcode);
                JSONObject jsonObject = JSONObject.fromObject(serviceStaff);
                net.sf.json.JSONArray items = jsonObject.getJSONArray("items");
                if (items != null && items.size() != 0) {
                    int staffId = 0;
                    for (int j = 0; j < items.size(); j++) {
                        JSONObject object = items.getJSONObject(j);
                        String contant = object.getString("contant");
                        if (contant.equals(orderDetailVo.getUserNameGet())) {
                            staffId = object.getInt("id");
                        }
                    }
                    if (staffId == 0) {
                    }
                    String userId = YuanTongUtils.getUser(DateUtil.dateToStr1(new Date()), vcode, "", 0, "", orderDetailVo.getIdCard());
                    if (userId.equals("2188433") || userId.equals("1384806")) {
                    }
                    YuanTongUtils.payService(endDataString,
                            (int) serviceId,
                            DateUtil.dateToStr1(new Date()),
                            vcode,
                            (int) staffId,
                            startDataString,
                            (String) userId,
                            orderDetailVo.getServiceName(),
                            orderDetailVo.getServiceName()+"服务",price);
                }
            }
        }

        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),result);
    }
    private int queryTfptService(String serviceName, String vcode) {
        if (serviceName.contains("颐嘉乐")){
            return 840964;
        }else if (serviceName.contains("颐佳乐")){
            return 840964;
        }else if (serviceName.contains("福康")){
            return 840626;
        }else{
            return 0;
        }
    }

    /**
     * 审批订单任务
     *
     * @param orderApprovalDto  order approval dto
     *
     * @return  the wrapper.
     */
    @RequestMapping(value = "/approval", method = RequestMethod.POST)
    public Wrapper approvalOrderTask(@RequestBody OrderApprovalDto orderApprovalDto) {

        //return WrapMapper.ok();
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null));
    }

    /**
     * 查询订单历史完成记录
     *
     * @return  the wrapper.
     */
    @RequestMapping(value = "/showHisFnsd", method = RequestMethod.POST)
    public Wrapper showOrderHisFnsd() {

        List<OrderVo> lists = omcOrderService.showOrderHisFnsd(getLoginAuthDto());

        //return WrapMapper.ok(lists);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),lists);
    }

    /**
     * 查询志愿者服务报告列表
     *
     * @return  the wrapper.
     */
    @RequestMapping(value = "/queryListWithPageByUserId", method = RequestMethod.POST)
    public Wrapper queryOrderListWithPageByUserId(@RequestBody OrderQueryDto orderQueryDto) {

        List<Integer> statList = Lists.newArrayList();
        statList.add(Constant.ORDER_STAT_CHECK_OUT);
        statList.add(Constant.ORDER_STAT_CONFIRM);
        statList.add(Constant.ORDER_STAT_CONFIRM_DELAY);

        orderQueryDto.setUserIdGet(getLoginAuthDto().getUserId());
        orderQueryDto.setStatList(statList);
        PageInfo pageInfo = omcOrderService.queryOrderListWithPage(orderQueryDto);

        //return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),pageInfo);
    }

    @RequestMapping(value = "/jpushSendMsg", method = RequestMethod.POST)
    public Wrapper jpushSendMsg(String tagList, Integer type) {

        Map<String, Object> map = Maps.newHashMap();
        map.put("msgType", "orderUpdate");

        String msg = "";
        switch (type) {
            case 1 :
                msg = Constant.ORDER_MESSAGE_WAIT;
                break;
            case 2 :
                msg = Constant.ORDER_MESSAGE_CHECK_IN_DELAY;
                break;
            case 3 :
                msg = Constant.ORDER_MESSAGE_CHECK_OUT_DELAY;
                break;
        }

        jpushService.sendToAll(msg,
                msg,
                msg,
                JSONObject.fromObject(map).toString(),
                Arrays.asList(tagList.split(",")));

        //return WrapMapper.ok();
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null));
    }
}
